<script setup>
  import { ref, reactive, onMounted } from 'vue';
  import { ElDialog, ElTable, ElTableColumn, ElPagination, ElInput, ElButton, ElSelect, ElOption, ElFormItem, ElForm } from 'element-plus';
  import { getEmployeeListAPI, createEmployeeAPI, editEmployAPI, editEmployIdAPI, delEmployeeAPI } from '@/api/employee';
  import { getRoleListAPI } from '@/api/system';
  import {Delete,Edit,Star} from '@element-plus/icons-vue'
  const employeeList = ref([]);
  // 分页查询数据
  const params = reactive({
    page: 1,
    pageSize: 10,
    name: '' // 员工姓名
  });
  const dialogVisible = ref(false); // 控制弹框打开关闭
  const roleList = ref([]); // 角色列表
  // 表单数据
  const addForm = reactive({
    name: '',
    phonenumber: '',
    roleId: '',
    status: 1,
    userName: ''
  });
  // 添加校验规则
  const addFormRules = reactive({
    name: [
      { required: true, message: '请输入员工姓名', trigger: 'blur' }
    ],
    userName: [
      { required: true, message: '请输入登录账号', trigger: 'blur' }
    ],
    phonenumber: [
      { required: true, message: '请输入联系方式', trigger: 'blur' }
    ],
    roleId: [
      { required: true, message: '请分配角色', trigger: 'blur' }
    ],
    status: [
      { required: true, message: '请选择员工状态', trigger: 'blur' }
    ]
  });
  const formRef = ref(null);// 表单校验
  const total = ref(0);
  
  onMounted(() => {
    getEmployeeList();
  });
  // 获取员工列表数据
  const getEmployeeList = async () => {
    const res = await getEmployeeListAPI(params);
    employeeList.value = res.data.rows;
    total.value = res.data.total;
  };
  // 改变显示页数
  const pageChange = (page) => {
    params.page = page;
    getEmployeeList();
  };
  // 关闭信息弹框
  const closeDialog = () => {
    dialogVisible.value = false;
    Object.assign(addForm, {
      id: null,
      name: '',
      userName: '',
      phonenumber: '',
      roleId: null,
      status: 1,
      // 其他字段的初始值...
    });
  };
  // 打开信息弹框
  const openDialog = async () => {
    const res = await getRoleListAPI();
    roleList.value = res.data;
  };
  // 点击添加员工，打开弹框
  const addEmployee = () => {
    console.log('开始添加');
    
    dialogVisible.value = true;
    
  };
  // 搜索按钮
  const doSearch = () => {
    // 1. 重置page为1
    params.page = 1;
    // 2. 调用获取列表接口
    getEmployeeList();
  };
  // 打开模态框，编辑数据
  const editEmployee = (row) => {
    dialogVisible.value = true;
    const { id, name, userName, roleId, roleName, status, phonenumber } = row;
    addForm.id = id;
    addForm.name = name;
    addForm.userName = userName;
    addForm.roleId = roleId;
    addForm.roleName = roleName;
    addForm.status = status;
    addForm.phonenumber = phonenumber;
  };
  // 添加数据
  const confirmAdd = async () => {
  if (!formRef || !formRef.value) return 
  try {
    // 执行表单校验
    const validateResult = await formRef.value.validate();
    if (!validateResult) {
      // 校验失败，可以在这里添加错误处理逻辑
      console.error('表单校验失败');
      return;
    }
    // 判断是增加还是编辑
    if (addForm.id) {
      // 调用编辑接口
      
      await editEmployAPI(addForm);

    } else {
      // 调用创建接口
      const { name, phonenumber,roleId,status,userName} = addForm
      await createEmployeeAPI({ name, phonenumber,roleId,status,userName});
    }
    // 显示成功信息
    ElMessage({
        type: 'success',
        message: `${addForm.id ? '编辑' : '添加'}角色成功`,
    })
    
    // // 清空表单
    formRef.value.resetFields();
    Object.assign(addForm, {
      id: null,
      name: '',
      userName: '',
      phonenumber: '',
      roleId: null,
      status: 1,
      // 其他字段的初始值...
    });
    // 关闭弹框
    dialogVisible.value = false;
    // 刷新列表
    getEmployeeList();
    
  } catch (error) {
    // 处理API调用错误
    console.log(error);
    
    ElMessage({
        type: 'error',
        message: error.response.data.msg,
    })
  }
};
// 重置密码，错误  
const editEmployeeId = async (id) => {
    await editEmployIdAPI(id);
    alert('重置密码成功');
  };
// 删除员工  
const delEmployee = async (id) => {

    ElMessageBox.confirm('删除员工后将不可登录，确认删除吗?').then(async () => {
      await delEmployeeAPI(id);
      ElMessage({
        type: 'success',
        message: '删除成功',
      })
      getEmployeeList();
    }).catch(() => {
      ElMessage({
        type: 'info',
        message: '删除取消',
      })
    

    })
  };
// 启用员工/禁用员工  
const formatStatus = (status) => {
    return status === 1 ? '启用' : '禁用';
  };
  </script>




<template>
    <div class="employee-container">
      <!-- 搜索区域 -->
      <div class="search-container">
        <div class="search-label">员工姓名：</div>
        <el-input v-model="params.name" clearable placeholder="请输入内容" class="search-main" @clear="doSearch" />
        <el-button type="primary" @click="doSearch(params.name)">查询</el-button>
      </div>
      <!-- 打开弹框，添加员工 -->
      <div class="create-container">
        <el-button type="primary" @click="addEmployee">添加员工</el-button>
      </div>
      <!-- 表格区域 -->
      <div class="table">
        <el-table style="width: 100%" :data="employeeList">
          <el-table-column type="index" label="序号" />
          <el-table-column label="员工姓名" width="180" prop="name" />
          <el-table-column label="登录账号" width="180" prop="userName" />
          <el-table-column label="联系方式" width="120" prop="phonenumber" />
          <el-table-column label="角色" width="180" prop="roleName" />
          <el-table-column label="状态">
            <template #default="scope">
              {{ formatStatus(scope.row.status) }}
            </template>
          </el-table-column>
          <el-table-column label="添加时间" prop="createTime" />
          <el-table-column label="操作" fixed="right" width="180">
            <template #default="scope">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top">
                    <el-button type="primary" :icon="Edit" circle  @click="editEmployee(scope.row)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                    <el-button type="danger" :icon="Delete" circle  @click="delEmployee(scope.row.id)"></el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="重置密码" placement="top">
                    <el-button type="warning" :icon="Star" circle @click="editEmployeeId(scope.row.id)"></el-button>
                </el-tooltip>
              
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 员工分页逻辑区域 -->
      <div class="page-container">
        <el-pagination
          layout="total, prev, pager, next"
          :page-size="params.pageSize"
          :total="total"
          @current-change="pageChange"
        />
      </div>
      <!-- 添加员工弹框 -->
      <el-dialog
        :title="addForm.id ? '编辑员工' : '添加员工'"
        v-model="dialogVisible"
        width="480px"
        @close="closeDialog"
        @open="openDialog"
      >
        <!-- 表单接口 -->
        <div class="form-container">
          <el-form :model="addForm" ref="formRef" :rules="addFormRules" label-width="80px">
            <el-form-item label="员工姓名" prop="name" >
              <el-input v-model="addForm.name"  />
            </el-form-item>
            <el-form-item label="登录账号" prop="userName" >
              <el-input v-model="addForm.userName"  />
            </el-form-item>
            <el-form-item label="联系方式"prop="phonenumber" >
              <el-input v-model="addForm.phonenumber"  />
            </el-form-item>
            <el-form-item label="分配角色" prop="roleId">
              <el-select v-model="addForm.roleId" placeholder="请选择角色">
                <el-option
                  v-for="item in roleList"
                  :key="item.roleId"
                  :label="item.roleName"
                  :value="item.roleId"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="员工状态" prop="status">
              <el-radio-group v-model="addForm.status">
                <el-radio :value="0">禁用</el-radio>
                <el-radio :value="1">启用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
        <template #footer>
          <el-button size="small" @click="dialogVisible = false">取 消</el-button>
          <el-button size="small" type="primary" @click="confirmAdd">确 定</el-button>
        </template>
      </el-dialog>
    </div>
  </template>
  

  
  <style scoped lang="scss">
  .employee-container {
    padding: 10px;
  }
  
  .search-container {
    display: flex;
    align-items: center;
    border-bottom: 1px solid rgb(237, 237, 237, .9);
    padding-bottom: 20px;
  
    .search-label {
      width: 100px;
    }
  
    .search-main {
      width: 220px;
      margin-right: 10px;
    }
  }
  .create-container{
    margin: 10px 0px;
  }
  .page-container{
    padding:4px 0px;
    text-align: right;
  }
  .form-container{
    padding:0px 80px;
  }
  </style>